package com.tbit.main.util;

import com.tbit.main.constant.AndWeather;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * HttpClient工具类
 *
 * @author Leon
 * 2019年1月23日 下午3:55:17
 */
@Slf4j
public class HttpClientUtil {
    public static String getResponse(InputStream input) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        StringBuffer stringBuffer = new StringBuffer();
        String str = "";
        while ((str = br.readLine()) != null) {
            stringBuffer.append(str);
        }

        return stringBuffer.toString();
    }

    /**
     * HTTP请求通过 & 拼接, 返回 URL
     * 请求地址 key: url
     *
     * @param map
     * @return
     */
    public static String urlJoint(Map<String, Object> map) {
        StringBuffer stringBuffer = new StringBuffer();
        for (Entry<String, Object> entry : map.entrySet()) {
            if ("url".equals(entry.getKey())) {
                stringBuffer.insert(0, entry.getValue() + "?");
                continue;
            }
            stringBuffer.append(entry.getKey() + "=" + entry.getValue());
            stringBuffer.append("&");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }

    /**
     * 发送post form请求
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String postForm(String url, Map<String, String> headers, Map<String, String> params) {

        String result = "";

        try {
            StringBuilder sbParams = new StringBuilder();
            for (Entry<String, String> entry : params.entrySet()) {
                sbParams.append(entry.getKey());
                sbParams.append("=");
                sbParams.append(entry.getValue().toString());
                sbParams.append("&");
            }
            if (sbParams.length() > 0) {
                sbParams.deleteCharAt(sbParams.lastIndexOf("&"));
            }

            URL reqUrl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection();

            //设置参数
            httpConn.setDoOutput(true);        //需要输出
            httpConn.setDoInput(true);        //需要输入
            httpConn.setUseCaches(false);    //不允许缓存
            httpConn.setRequestMethod("POST");        //设置POST方式连接

            //设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setRequestProperty("accept", "*/*");

            if (headers != null) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    httpConn.setRequestProperty(entry.getKey(), entry.getValue().toString());
                }
            }

            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            //dos.writeBytes(sbParams.toString()); 这个方法会有中文乱码
            dos.write(sbParams.toString().getBytes("utf-8")); //解决中文乱码
            dos.flush();
            dos.close();

            if (httpConn.getResponseCode() != 200) {
                throw new RuntimeException("HTTP POST form Request Failed with Error code : "
                        + httpConn.getResponseCode() + " url:" + url + " form:" + params.toString());
            }

            InputStream inputStream = httpConn.getInputStream();
            result = readAll(inputStream);
            inputStream.close();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * json格式数据提交
     *
     * @param url
     * @param json
     * @throws IOException
     */
    public static String httpJson(String url, String json) throws IOException {
        final String CONTENT_TYPE_TEXT_JSON = "text/json";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");

        StringEntity se = new StringEntity(json, "UTF-8");
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        CloseableHttpResponse response2 = null;
        response2 = httpClient.execute(httpPost);
        HttpEntity entity2 = null;
        entity2 = response2.getEntity();
        String s2 = EntityUtils.toString(entity2, "UTF-8");

        return s2;

    }

    /**
     * 发送json请求
     *
     * @param url
     * @param headers
     * @param jsonData
     * @return
     */
    public static String postJSON(String url, Map<String, Object> headers, String jsonData) {

        String result = "";

        try {

            URL reqUrl = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection();

            //设置参数
            httpConn.setDoOutput(true);        //需要输出
            httpConn.setDoInput(true);        //需要输入
            httpConn.setUseCaches(false);    //不允许缓存
            httpConn.setRequestMethod("POST");        //设置POST方式连接

            //设置请求属性
            httpConn.setRequestProperty("Content-Type", "application/json");
            httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            httpConn.setRequestProperty("Charset", "UTF-8");
            httpConn.setRequestProperty("accept", "*/*");

            if (headers != null) {
                for (Entry<String, Object> entry : headers.entrySet()) {
                    httpConn.setRequestProperty(entry.getKey(), entry.getValue().toString());
                }
            }

            //建立输入流，向指向的URL传入参数
            DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
            //dos.writeBytes(jsonData); 这个方法会有中文乱码,使用下面的方法解决
            dos.write(jsonData.getBytes("utf-8"));
            dos.flush();
            dos.close();

            if (httpConn.getResponseCode() != 200) {
                throw new RuntimeException("HTTP POST json Request Failed with Error code : "
                        + httpConn.getResponseCode() + " url:" + url + " json:" + jsonData);
            }

            InputStream inputStream = httpConn.getInputStream();
            result = readAll(inputStream);
            inputStream.close();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 读取字节流
     *
     * @param inputStream
     * @return
     */
    private static String readAll(InputStream inputStream) {

        StringBuilder builder = new StringBuilder();

        try {
            byte[] b = new byte[1024];
            int length = -1;
            while ((length = inputStream.read(b)) != -1) {
                builder.append(new String(b, 0, length, "UTF-8"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String httpGet(String url) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet = null;
        try {
            httpClient = HttpClients.createDefault();
            httpGet = new HttpGet(url);
            //httpGet.addHeader("checkSum", checkSum);
            String respContent = null;

            //设置超时5s
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
            httpGet.setConfig(requestConfig);

            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = response.getEntity();
                respContent = EntityUtils.toString(he, "UTF-8");
            }
            return respContent;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
	/*	String url = "http://192.168.1.22:8083/accountDayStat/operationalDataToMain.do";
		Long time = System.currentTimeMillis();
		String sign = SingUtil.createSing("tbit123456" + time);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("startTime", DateTimeUtil.DateToString(new Date()));
		map.put("endTime",DateTimeUtil.DateToString(new Date()));
		map.put("accountIds", "11952");
		map.put("brandId","100001");
		map.put("time", time);
		map.put("sign",sign);
		System.out.println(HttpUtil.get(url, map));*/


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("url", AndWeather.business);
        map.put("location", "112.86335297916665,27.24696009722224");
        map.put("key", AndWeather.key);
        System.out.println(HttpClientUtil.httpGet(HttpClientUtil.urlJoint(map)));
    }

}
